package cn.demoframe.test.frame.controller;

import cn.demoframe.test.frame.model.MenuInfo;
import cn.demoframe.test.frame.model.RoleInfo;
import cn.demoframe.test.frame.service.MenuinfoService;
import cn.demoframe.test.frame.service.RoleinfoService;
import cn.demoframe.test.frame.vmodel.RoleForm;
import cn.demoframe.test.model.Griddata;
import cn.demoframe.test.model.Griddata_pageinfo;
import cn.demoframe.test.model.Listitem;
import cn.demoframe.test.model.Message;
import cn.demoframe.test.model.Treenode;
import cn.demoframe.test.utils.Constants;
import cn.demoframe.test.utils.DateToolkit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class RoleController {
    private static final Logger logger = LoggerFactory.getLogger(Thread
            .currentThread().getStackTrace()[1].getClassName());

    @Resource(name = "RoleinfoServiceImpl")
    private RoleinfoService roleinfoService;
    
    @Resource(name = "MenuinfoServiceImpl")
    private MenuinfoService menuinfoService;

    @RequestMapping(value = "/auth/roleinfo/getroleinfolist", method = RequestMethod.POST)
    @ResponseBody
    public List<Listitem> getRoleinfoList() {
        logger.debug("获取角色信息列表");
        List<RoleInfo> rolelist = roleinfoService.getRoleInfos(
                null, null, null);
        List<Listitem> itemlist = new ArrayList<Listitem>();
        Listitem i;
        for (RoleInfo r : rolelist) {
            i = new Listitem();
            i.setText(r.getRolenm());
            i.setId(r.getRoleid());
            itemlist.add(i);
        }
        return itemlist;
    }

    @RequestMapping(value = "/auth/roleinfo/getroleinfos", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Griddata_pageinfo getRoleinfos() {
        logger.debug("获取角色信息");
        List<RoleInfo> rolelist = roleinfoService.getRoleInfos(
                null, null, null);
        return new Griddata_pageinfo(rolelist.size(), rolelist);
    }

    /**
     * 获取角色权限树节点
     * @return 节点列表
     */
    @RequestMapping(value = "/auth/roleinfo/getrolenodes", method = RequestMethod.POST)
    @ResponseBody
    public List<Treenode> getRoleNodes(
            @RequestParam(value = "roleid") String roleid) {
        logger.debug("获取角色权限树节点");
        RoleInfo r = roleinfoService.getRoleInfos(roleid, null, null).get(0);
        String lmt = r.getLmtserial();

        List<MenuInfo> tmpnodes = menuinfoService.getMenuInfos(null, null, null, "POSITION ASC");
        List<Treenode> tmptitlelist = new ArrayList<Treenode>();
        for (MenuInfo t : tmpnodes) {// 筛选标题节点
            if (t.getNodetype().equals("0")) {
            	Treenode t2 = new Treenode();
                t2.setId(t.getMenuid().toString());
                t2.setName(t.getTitle());
				if (lmt.charAt(t.getMenuid()) == '1') {// 判断角色是否拥有权限
					t2.setChecked(true);
				} else {
					t2.setChecked(false);
				}
                t2.setSpread(true);
                tmptitlelist.add(t2);
            }
        }

        List<Treenode> titlelist = new ArrayList<Treenode>();
        for (Treenode tmp : tmptitlelist) {// 为每个标题节点填充子节点
            List<Treenode> children = new ArrayList<Treenode>();
            for (MenuInfo t : tmpnodes) {// 填充子节点
                if (tmp.getId().equals(t.getParentid().toString())) {
                	Treenode sub = new Treenode();
                    sub.setId(t.getMenuid().toString());
                    sub.setName(t.getTitle());
                    if (lmt.charAt(t.getMenuid()) == '1') {// 判断角色是否拥有权限
                        sub.setChecked(true);
                    } else {
                        sub.setChecked(false);
                    }
                    children.add(sub);
                }
            }
            tmp.setChildren(children);
            titlelist.add(tmp);
        }

        return titlelist;
    }

    /**
     * 修改角色权限
     * @return 信息
     */
    @RequestMapping(value = { "/auth/roleinfo/modrole" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message modRole_log(HttpServletRequest request,
            @RequestParam(value = "roleid") String roleid,
            @RequestParam(value = "ids") String ids) {
    	Message m = new Message();
        try {
			StringBuilder lmt = new StringBuilder();
			for (int i = 0; i < Constants.NODE_NUM_MAX; i++) {
			    lmt.append("0");
			}
			String[] id = ids.split(",");
			for (String s : id) {
			    int offset = Integer.parseInt(s);
			    lmt.setCharAt(offset, '1');
			}
			logger.debug("修改后的角色权限字符串：" + lmt.toString());
			roleinfoService.modRoleInfo(roleid, null, lmt.toString());
			m.setResult("00");
			m.setDetail("角色权限已修改.");
		} catch (Exception e) {
			m.setResult("99");
			m.setDetail("角色权限修改失败.");
			logger.error("角色权限修改失败.", e);
		}
        return m;
    }

    /**
     * 新增角色
     * @param model 模型
     * @return 信息
     */
    @RequestMapping(value = { "/auth/roleinfo/addrole" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message addRole_log(HttpServletRequest request, HttpEntity<RoleForm> model) {
        logger.debug("新增角色");
        Message m = new Message();
        RoleForm rf = model.getBody();
        int num = roleinfoService.getRoleInfosCount(rf.getRoleid(), null);
        if (num > 0) {
            m.setResult("99");
            m.setDetail("角色已存在.");
            return m;
        }

        try {
			StringBuilder lmt = new StringBuilder();
			for (int i = 0; i < Constants.NODE_NUM_MAX; i++) {
			    lmt.append("0");
			}
			RoleInfo r = new RoleInfo();
			r.setRoleid(rf.getRoleid());
			r.setRolenm(rf.getRolenm());
			r.setLmtserial(lmt.toString());
            r.setCreatetime(DateToolkit.Date2String(new Date(), DateToolkit.YYYY_MM_DD_HH24_MM_SS));

			roleinfoService.addRoleInfo(r);
			m.setResult("00");
			m.setDetail("角色新增成功.");
		} catch (Exception e) {
			m.setResult("99");
			m.setDetail("角色新增失败.");
			logger.error("角色新增失败.", e);
		}

        return m;
    }

    /**
     * 删除角色
     * @param roleid 角色ID
     * @return 信息
     */
    @RequestMapping(value = { "/auth/roleinfo/delrole" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message delRole_log(HttpServletRequest request,
            @RequestParam(value = "roleid") String roleid) {
        logger.debug("删除角色");
        Message m = new Message();
        try {
			roleinfoService.delRoleInfo(roleid);
			m.setResult("00");
			m.setDetail("角色已删除.");
		} catch (Exception e) {
			m.setResult("99");
			m.setDetail("角色删除失败.");
			logger.error("角色删除失败.", e);
		}
        return m;
    }

}
